import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, message } from 'antd';
import axios from '@/components/service/request';

const EditModal = ({ record, onUpdate, visible, onClose }) => {
    const [form] = Form.useForm();

    useEffect(() => {
        // 当模态框打开时，设置表单的初始值
        if (visible) {
            form.setFieldsValue({
                remark: record?.remark || ''  // 如果 remark 为 undefined 或 null，则设置为空字符串
            });
        }
    }, [record, visible]);

    const handleSave = () => {
        form.validateFields()
            .then(values => {
                const updatedRecord = { 
                    ...record, 
                    remark: values.remark,
                    data: record.data, // 确保 data 格式正确
                    userId: record.userId,
                    state: record.state,
                    filePath: record.filePath
                };

                axios.post('/filedata/update', updatedRecord)  // 传递整个 FileDate 对象
                    .then(() => {
                        onUpdate(updatedRecord);  // 通知父组件更新数据
                        message.success('编辑成功');
                    })
                    .catch(error => {
                        console.error('Error updating record:', error);
                        message.error('编辑失败');
                    });
                onClose();  // 关闭模态框
            });
    };

    return (
        <Modal
            title="编辑备注"
            visible={visible}
            onOk={handleSave}
            onCancel={onClose}
        >
            <Form form={form} layout="vertical">
                <Form.Item
                    name="remark"
                    label="备注"
                    rules={[{ required: true, message: '请输入备注' }]}
                >
                    <Input />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default EditModal;
